//
//  IWPopMenu.m
//  8期微博
//
//  Created by apple on 14-9-1.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

#import "TTPopMenuView.h"

@interface TTPopMenuView()
/**
 *  需要显示的内容
 */
@property (nonatomic, strong) UIView *contentView;
/**
 *  遮盖
 */
@property (nonatomic, weak) UIButton *cover;
/**
 *  菜单容器
 */
@property (nonatomic, weak) UIImageView *containerView;
@end

@implementation TTPopMenuView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 1.添加遮盖
        UIButton *cover = [[UIButton alloc] init];
        cover.backgroundColor = [UIColor clearColor];
        [cover addTarget:self action:@selector(coverBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cover];
        self.cover = cover;
        
        // 2.添加菜单
        UIImageView *containerView = [[UIImageView alloc] init];
        containerView.image = [UIImage resizableImageWithName:@"popover_background" leftRatio:0.54 topRatio:0.5];
        containerView.userInteractionEnabled = YES;
        [self addSubview:containerView];
        self.containerView = containerView;
        
    }
    return self;
}

+ (instancetype)popMenuContentView:(UIView *)contentView
{
    return [[self alloc] initWithContentView:contentView];
}

- (instancetype)initWithContentView:(UIView *)contentView
{
    if (self = [super init]) {
        // 初始化操作
        self.contentView = contentView;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 设置遮盖的frame
    self.cover.frame = self.bounds;
}

- (void)show:(CGRect)rect
{
    // 1.设置自己的frame等于window frame
    // 注意, 以后在使用window的时候尽量使用application获取, 不要直接view.window
    // 直接通过控制器的view获取有可能获取不到window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.frame = window.bounds;
    
    // 2.设置容器的frame
    self.containerView.frame = rect;
    
    // 3.添加需要显示的内容到容器中
    [self.containerView addSubview:self.contentView];
    
    // 4.调整内容视图的frame
    CGFloat contentX = 5;
    CGFloat contentY = 15;
    CGFloat contentMargin = contentX;
    
    self.contentView.x = contentX;
    self.contentView.y = contentY;
    self.contentView.width = self.containerView.width - 2 * contentMargin;
    self.contentView.height = self.containerView.height - contentY - contentMargin;
    
    // 2.将自己添加到父控件中
    [window addSubview:self];
    
}
- (void)dismiss
{
    // 1.将直接从父控件中移除
    [self removeFromSuperview];
}

#pragma mark - 内部方法
- (void)coverBtnClick
{
    IWLog(@"coverBtnClick");
    // 2.通知代理
    if ([self.delegate respondsToSelector:@selector(popMenuViewDidClick:)]) {
        [self.delegate popMenuViewDidClick:self];
    }
    
    // 1.移除菜单
    [self dismiss];
    
    
}

- (void)setContainerViewBg:(UIImage *)image
{
    self.containerView.image = image;
}
@end
